<style>
 .el-tree{
width: 100%;
overflow-x: scroll;
height: 720px;
}
.el-tree>.el-tree-node{
display: inline-block !important;
}
</style>

<template>
	<section>
		<el-row>
			<!--工具条-->
			<el-col :span="23" class="toolbar toolMarginTop" id="serachId">
				<el-form :inline="true" :model="filters">
					<el-button v-hasPermission="'add'" type="primary" @click="organizationAdd"  size="small" style="float:left;">新增部门</el-button>
					<el-form-item style="float:right">
						<el-button type="primary" v-on:click="doGetMyOrgsList" size="small">查询</el-button>
					</el-form-item>
					<el-form-item style="float:right">
						<el-input v-model="filters.name" placeholder="请输入部门名称" size="small" @keyup.enter.native="searchEnterFun"></el-input>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row class="tac titleLineSymbolTwo">
			<el-col :span="4">
				<el-tree @node-click="toGetList" :data="treeData" node-key="orgSerialNo" ref="tree"
						 highlight-current :props="defaultProps">
				</el-tree>
			</el-col>
			<el-col :span="19" >
				<!--列表-->
				<el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
					<el-table-column type="index" label="序号" >
					</el-table-column>
					<el-table-column prop="name" label="部门名称" width="370">
					</el-table-column>
					<el-table-column prop="parentOrganizationName" label="上级部门" width="350">
					</el-table-column>
					<el-table-column prop="status" label="部门状态" :formatter="formatStatus" width="210">
					</el-table-column>
					<el-table-column prop="telephone" label="办公室电话" >
					</el-table-column>
					<el-table-column label="操作" width="200" fixed="right">
						<template slot-scope="scope">
                            <el-button type="text" size="small" @click="userDetails(scope.$index, scope.row)">查看</el-button>
							<el-button v-hasPermission="'edit'" type="text" size="mini" @click="organizationEdit(scope.$index, scope.row)">修改</el-button>
							<el-button v-hasPermission="'del'" type="text" size="mini" @click="organizationDelete(scope.$index, scope.row)">删除</el-button>
							<!--------------------------------------------------------------------------------- todo 用户无法理解这两个按钮有什么用，其实是用来给应用授权子页面数据做关联的，考虑用只有admin可见的方式去做 start -------------------------------------------------------------------------------------->
							<!--<el-button type="text" size="small" @click="roleAuthorizationView(scope.$index, scope.row)">角色授权</el-button>-->
							<!--<el-button type="text" size="small" @click="policeAuthorizationView(scope.$index, scope.row)">警种授权</el-button>-->
							<!--------------------------------------------------------------------------------- todo 用户无法理解这两个按钮有什么用，其实是用来给应用授权子页面数据做关联的，考虑用只有admin可见的方式去做 end -------------------------------------------------------------------------------------->
						</template>
					</el-table-column>
				</el-table>
				<!--工具条-->
				<el-col :span="23" class="toolbar marginTop10px">
					<el-pagination layout="total, prev, pager, next, jumper" @current-change="handleCurrentPageChange"
								   :current-page="pageNum" :page-size="pageSize" :total="total">
					</el-pagination>
				</el-col>
			</el-col>
		</el-row>
        <Modal title="组织详情" v-model="viewVisible" width="50%">
            <view-detail
                :viewForm="viewForm">
            </view-detail>
        </Modal>
		<!--编辑界面-->
		<!-- <el-dialog title="组织机构编辑" :visible.sync="editFormVisible" :modal-append-to-body="false"> -->
		<Modal v-model="editFormVisible" title="组织机构编辑" width='50%'>
			<el-card>
				<el-form :model="editForm" label-width="120px" ref="editForm" :rules="formRules">
					<el-row>
						<el-col :span="12">
							<el-form-item label="部门名称">
								<el-input v-model="editForm.name" placeholder="不能超过50个汉字"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="部门编码">
								<el-input v-model="editForm.orgSerialNo" placeholder="系统自动生成" :disabled="true"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="上级部门">
								<el-select placeholder="请选择" v-model="editForm.parentSerialNo">
									<el-option v-for="item in organizations" :key="item.orgSerialNo" :label="item.name" :value="item.orgSerialNo">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="排序">
								<el-input v-model="editForm.orderNo"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="办公室电话">
								<el-input v-model="editForm.telephone"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</Modal>
		<!--新增界面-->
		<Modal v-model="addFormVisible" title="组织机构注册" width='50%' >
			<el-card>
				<el-form :model="addForm" label-width="120px" ref="addForm" :rules="formRules">
					<el-row>
						<el-col :span="12">
							<el-form-item label="部门名称" prop="name">
								<el-input v-model="addForm.name" placeholder="不能超过50个汉字"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="部门编码">
								<el-input v-model="addForm.orgSerialNo" placeholder="系统自动生成" :disabled="true"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="上级部门" prop="parentSerialNo">
								<el-select placeholder="请选择" v-model="addForm.parentSerialNo" >
									<el-option v-for="item in organizations" :key="item.orgSerialNo" :label="item.name" :value="item.orgSerialNo">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="排序">
								<el-input v-model="addForm.orderNo"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="办公室电话" prop="telephone">
								<el-input v-model="addForm.telephone"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</Modal>
		<!-- 角色授权 -->
		<Modal v-model="roleAuthorizationDig" title="角色授权" width='50%'>
			<el-card class="treeCard">
				<el-tree :data="jstreeData" show-checkbox node-key="serialNo" :default-expanded-keys="jsShowData" ref="jstree"
						 highlight-current :props="defaultProps_js">
				</el-tree>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="roleAuthorizationDig = false">取消</el-button>
				<el-button type="primary" @click.native="roleAuthorizationSubmit" :loading="roleAuthorizationLoading">提交</el-button>
			</div>
		</Modal>
		<!-- 警种授权 -->
		<Modal v-model="policeAuthorizationDig" title="警种授权" width='50%'>
			<el-card class="treeCard">
				<el-tree :data="policetreeData" show-checkbox node-key="id" :default-expanded-keys="policeShowData" ref="policetree"
						 highlight-current :props="defaultProps_police">
				</el-tree>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="policeAuthorizationDig = false">取消</el-button>
				<el-button type="primary" @click.native="policeAuthorizationSubmit" :loading="policeAuthorizationLoading">提交</el-button>
			</div>
		</Modal>
	</section>
</template>

<script>
    import util from '../../app-market/api/util';
    import message from '../../api/message';
    // import NProgress from 'nprogress'
    import viewDetail from "./components/viewDetail.vue";
    import { getOrganizationList, addOrganization, editOrganization, deleteOrganization ,getMyOrgsList, getree,
        getRoleList, roleOrgSeach, roleOrgUpdate, getDictionaryList, policeeOrgSeach, policeeOrgUpdate} from '../../api/api';

    export default {
        data () {
            return {
                filters: {
                    name: ''
                },
                tableData: [],
                treeData:[],
                total: 0,
                pageNum: 1,
                pageSize: 10,
                listLoading: false,

                organizations:[],//所有部门数组

                editFormVisible: false, // 编辑界面是否显示
                viewVisible: false,
                viewForm: {},
                editLoading: false,
                // 编辑界面数据
                editForm: {
                    parentSerialNo: '',
                    orgNum:'',
                    name: '',
                    description: '',
                    status: 0,
                    address: '',
                    telephone: '',
                    icode:'',
                    code:'',
                    orderNo:100,
                    type:0,
                    level:'',
                    isDeleted:'',
                    source:''
                },

                addFormVisible: false, // 新增界面是否显示
                addLoading: false,

                // 新增界面数据
                addForm: {
                    parentSerialNo: '',
                    orgNum:'',
                    name: '',
                    description: '',
                    status: 0,
                    address: '',
                    telephone: '',
                    icode:'',
                    code:'',
                    orderNo:100,
                    type:0,
                    level:'',
                    isDeleted:'',
                    source:''
                },
                defaultProps: {
                    id:'orgSerialNo',
                    label: 'name',
                    children: 'organizationVos',
                },
                orgSerialNo:"",
                //角色授权
                roleAuthorizationDig:false,
                roleAuthorizationLoading:false,
                jstreeData:[],
                jsShowData:[],
                defaultProps_js: {
                    label: 'roleName'
                },
                policeAuthorizationDig:false,
                policeAuthorizationLoading:false,
                policetreeData:[],
                policeShowData:[],
                defaultProps_police: {
                    label: 'name'
                },
                //表单校验规则
                formRules: { // 新增界面校验规则
                    parentSerialNo: [
                        {required: true, message: '请选择上级部门', trigger: 'blur'}
                    ],
                    name: [
                        {required: true, message: '请选择上级部门', trigger: 'blur'}
                    ],
                    orgNum: [
                        {required: true, message: '请输入部门编码', trigger: 'blur'}
                    ],
                    icode: [
                        {required: true, message: '请输入编码序号', trigger: 'blur'}
                    ],
                    type: [
                        {required: true, message: '请选择类型', trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请选择状态', trigger: 'blur'}
                    ],

                },
            };
        },
        components: {
            viewDetail
        },
        methods: {
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            formatStatus: function (row, column) {
                if (row.status == 0) {
                    return '禁用';
                } else if (row.status == 1) {
                    return '启用';
                } else if (row.status == 2) {
                    return '未审核';
                } else {
                    return '未知';
                }
            },
            handleCurrentPageChange: function (pageNum) { // 翻页动作
                this.pageNum = pageNum;
                this.doGetMyOrgsList();// 翻页后刷新页面数据
            },
             //实现回车键搜索功能
			searchEnterFun:function(e){
				this.doGetMyOrgsList();
            },
            // 获取 自己的 组织机构 列表
            doGetMyOrgsList () {
                let params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    name: this.filters.name,
                    orgSerialNo:this.$refs.tree.getCurrentKey()
                };
                this.listLoading = true;
                // NProgress.start();
                getMyOrgsList(params).then(function (result) {
                    this.tableData = result.data.data.list;
                    this.pageNum = result.data.data.pageNum;
                    this.pageSize = result.data.data.pageSize;
                    this.total = result.data.data.total;
                    //this.organizations = result.data.data.list;
                    this.listLoading = false;
                }.bind(this)).catch(function (error) {
                    this.listLoading = false;
                    console.log(error);
                }.bind(this));
            },
            getree() {
                let params = {};
                getree(params).then(function(result){
                    this.treeData = result.data;
                }.bind(this)).catch(function (error) {
                }.bind(this));
            },
            toGetList:function(){
                this.doGetMyOrgsList();
            },
            // 删除
            organizationDelete: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    deleteOrganization(row.orgId).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.doGetMyOrgsList();
                    });
                }).catch(() => {
                    this.$message.error('删除失败!');
                });
            },
            // 显示编辑界面
            organizationEdit: function (index, row) {
                this.getOrganizations();
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            userDetails(index,row){
                this.viewVisible = true;
                this.viewForm = Object.assign({}, row);
            },
            // 显示新增界面
            organizationAdd: function () {
                this.addForm = {
                    parentSerialNo: '',
                    orgNum:'',
                    name: '',
                    description: '',
                    status: 0,
                    address: '',
                    telephone: '',
                    icode:'',
                    code:'',
                    orderNo:100,
                    type:0,
                    level:'',
                    isDeleted:'',
                    source:''
                };
                this.getOrganizations();
                this.addFormVisible = true;
            },
            //查询组织机构
            getOrganizations: function () {
                let params = {
                    pageNum: 1,
                    pageSize: 10000
                };
                getOrganizationList(params).then(function (result) {
                    this.organizations = result.data.data.list;
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            // 编辑
            editSubmit: function () {
                
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            // NProgress.start();
                            let params = Object.assign({}, this.editForm);
                            params.createDate = Date.parse(new Date(params.createDate));
                            editOrganization(params).then((res) => {
                                this.editLoading = false;
                                // NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.doGetMyOrgsList();
                            });
                        });
                    }
                });
            },
            // 新增
            addSubmit: function () {
                // if(this.addForm.roleName.length>20){
                //     this.$message({
                //         message: '不能超过50个汉字',
                //         type: 'info'
                //     });
                //     return;
                // }
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            // NProgress.start();
                            let params = Object.assign({}, this.addForm);
                            // if(params.parentSerialNo === null || params.parentSerialNo === '') {
                            // 	params.parentSerialNo = -1;
                            // }
                            addOrganization(params).then((res) => {
                                this.addLoading = false;
                                // NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.doGetMyOrgsList();
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //查询角色
            getroles: function () {
                let params = {
                    pageNum: 1,
                    pageSize: 10000
                };
                getRoleList(params).then(function(result){
                    this.jstreeData = result.data.data.list;
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            roleAuthorizationView: function(index, row) {
                let _this = this;
                this.orgSerialNo = row.orgSerialNo;
                let params = {
                    orgSerialNo: row.orgSerialNo
                };
                roleOrgSeach(params).then(function(result){
                    if(result.data.code === "B104001"){
                        this.$message({
                            message: result.data.msg,
                            type: 'info'
                        });
                    }else{
                        result.data.data.list.forEach(obj => {
                            _this.jsShowData.push(obj.serialNo);
                        });
                        _this.roleAuthorizationDig = true;
                        setTimeout(function(){
                            _this.$refs.jstree.setCheckedNodes(result.data.data.list);
                        },100);
                    }
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            roleAuthorizationSubmit: function() {
                let allNodes = this.$refs.jstree.getCheckedNodes();
                let roleArr = [];
                allNodes.forEach(obj => {
                    roleArr.push(obj.id);
                });
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    this.departmentAuthorizationLoading = true;
                    let params = {
                        pageNum: 1,
                        pageSize: 10000,
                        orgSerialNo : this.orgSerialNo,
                        roleIds : roleArr
                    }
                    roleOrgUpdate(params).then((res) => {
                        this.roleAuthorizationLoading = false;
                        message.msg(res,this,true);
                        this.roleAuthorizationDig = false;
                        this.doGetMyOrgsList();
                    });
                });
            },
            //查询警种
            getPolices: function () {
                let params = {
                    pageNum: 1,
                    pageSize: 10000,
                    type:'jobCategory'
                };
                getDictionaryList(params).then(function(result){
                    this.policetreeData = result.data.data.list;
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            policeAuthorizationView: function(index, row) {
                let _this = this;
                this.orgSerialNo = row.orgSerialNo;
                let params = {
                    orgSerialNo: row.orgSerialNo
                };
                policeeOrgSeach(params).then(function(result){
                    if(result.data.code === "B104001"){
                        this.$message({
                            message: result.data.msg,
                            type: 'info'
                        });
                    }else{
                        result.data.data.list.forEach(obj => {
                            _this.policeShowData.push(obj.id);
                        });
                        _this.policeAuthorizationDig = true;
                        setTimeout(function(){
                            _this.$refs.policetree.setCheckedNodes(result.data.data.list);
                        },100);
                    }
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
            },
            policeAuthorizationSubmit: function() {
                let allNodes = this.$refs.policetree.getCheckedNodes();
                let policeArr = [];
                allNodes.forEach(obj => {
                    policeArr.push(obj.id);
                });
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    this.departmentAuthorizationLoading = true;
                    let params = {
                        pageNum: 1,
                        pageSize: 10000,
                        orgSerialNo : this.orgSerialNo,
                        distionaryIds : policeArr
                    }
                    policeeOrgUpdate(params).then((res) => {
                        this.policeAuthorizationLoading = false;
                        message.msg(res,this,true);
                        this.policeAuthorizationDig = false;
                        this.doGetMyOrgsList();
                    });
                });
            },
        },
        mounted () {
            this.doGetMyOrgsList();
            this.getree();
            this.getroles();
            this.getPolices();
        }
    };
</script>
